from django.template import RequestContext
from django.shortcuts import render_to_response
from models import Movie
from RSM.util import getRSMUser, verifySessionValidity, printDebug, getTitle


def viewMovieTypes(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    __updateUserMoviesList(request.user.username, request.POST.getlist(u'selectedList'), request.POST.get(u'movieType'))
    return render_to_response("my_movies/movieTypes.html",context_instance=RequestContext(request))
    
def viewMovies(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    movieType = request.POST["movieType"]
    movieNames = []
    currentUser = getRSMUser(request.user.username)
    
    allMovies = set(Movie.objects.all())
    if movieType == "Seen":
        movieNames = [u.title for u in currentUser.seen.all()]
    elif movieType == "Likes":
        movieNames = [u.title for u in currentUser.likes.all()]
        allMovies -= set(currentUser.blacklist.all())
    elif movieType == "Blacklist":
        movieNames = [u.title for u in currentUser.blacklist.all()]
        allMovies -= set(currentUser.likes.all())
    else:
        printDebug('BUG in my_movies view: viewMovies')
    
    variables = {"movienames": movieNames, "movietype": movieType, "allmovies": map(getTitle, allMovies)}
    return render_to_response("my_movies/viewmovies.html", variables, context_instance=RequestContext(request))



def __updateUserMoviesList(username, selectedList, movieType):
    if not movieType:
        return
    currentUser = getRSMUser(username)
    if movieType == "Seen": 
        list = currentUser.seen
    elif movieType == "Likes":
        list = currentUser.likes
    elif movieType == "Blacklist":
        list = currentUser.blacklist
    else:
        printDebug('BUG in my_movies view: __updateUserMoviesList')
    
    list.clear()
    for m in selectedList:
        list.add(Movie.objects.get(title=m))
